import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('lena.jpg')

rows,cols = img.shape[:2]

###仿射变换

#需要图像、变换矩阵、变换后的大小

pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
M = cv2.getAffineTransform(pts1,pts2)
res = cv2.warpAffine(img,M,(rows,cols))

M2 = cv2.getAffineTransform(pts2,pts1)
recovered = cv2.warpAffine(res,M2,(rows,cols))

b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
p1 = plt.subplot(131)
p1.set_title("org image",fontsize=12)
p1.imshow(img2)

b,g,r = cv2.split(res)
res2 = cv2.merge([r,g,b])
p2 = plt.subplot(132)
p2.set_title("new image",fontsize=12)
p2.imshow(res2)

b,g,r = cv2.split(recovered)
recovered2 = cv2.merge([r,g,b])
p3 = plt.subplot(133)
p3.set_title("recovered image",fontsize=12)
p3.imshow(recovered2)

plt.show()


###透视变换

pts1 = np.float32([[56,65],[238,52],[28,237],[239,240]])
pts2 = np.float32([[0,0],[200,0],[0,200],[200,200]])
M = cv2.getPerspectiveTransform(pts1,pts2)
res = cv2.warpPerspective(img,M,(rows,cols))

M2 = cv2.getPerspectiveTransform(pts2,pts1)
recovered = cv2.warpPerspective(res,M2,(rows,cols))


b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
p1 = plt.subplot(131)
p1.set_title("org image",fontsize=12)
p1.imshow(img2)

b,g,r = cv2.split(res)
res2 = cv2.merge([r,g,b])
p2 = plt.subplot(132)
p2.set_title("new image",fontsize=12)
p2.imshow(res2)

b,g,r = cv2.split(recovered)
recovered2 = cv2.merge([r,g,b])
p3 = plt.subplot(133)
p3.set_title("recovered image",fontsize=12)
p3.imshow(recovered2)

plt.show()